package com.ys.controller.web.base;

import com.ys.config.MenuId;
import com.ys.config.MyConfig;
import com.ys.entity.base.TbUserJobLevelManage;
import com.ys.entity.base.TbUserTaxManage;
import com.ys.entity.base.TbUserTaxManageItem;
import com.ys.entity.base.TbUserTaxRate;
import com.ys.service.sys.CommonApiService;
import com.ys.vo.W;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 员工职级管理
 */
@Controller
@RequestMapping("/web/base/tbUserJobLevelManage")
public class WebTbUserJobLevelManageController {
	private static final Logger logger = LoggerFactory.getLogger(WebTbUserJobLevelManageController.class);

	@Autowired
	private CommonApiService<TbUserJobLevelManage> commonApiService;


    public Map<String, Object> getEntity(Long id){
        Map<String,Object> entity = new TbUserJobLevelManage()
            .addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS _ys_nameLinked")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo OI ON OI.Orgid = U.DeptId")
                .addField("OI.DeptName AS deptName")//部门

            .addLeftJoin("THR_UserArchives UA ON UA.UserId = A.UserId")//用户档案表
                .addField("UA.UserState AS userState")//员工状态
                .addField("CASE " +
                        "WHEN UA.UserState = 0 THEN '实习' " +
                        "WHEN UA.UserState = 1 THEN '试用' " +
                        "WHEN UA.UserState = 2 THEN '正式' " +
                        "WHEN UA.UserState = 3 THEN '离职' " +
                        " ELSE '' END userStateTxt")//员工状态（0实习、1试用、2正式、3离职）
                .addField("UA.DingDingId AS dingDingId")//员工钉钉id
                .addField("UA.Telephone AS telephone")//联系电话

            .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表
                .addField("O.OrgName AS orgName")//所属公司

            .addLeftJoin("TB_JobLevel J ON J.Id = A.RoleLevelId")//岗位职级表
                .addField("J.Rank AS rank")//岗位职级
                .addField("J.Category AS category")//岗位类别
                .addField("J.Categories AS categories")//职级大类
                .addField("J.Type AS roleLevelType")//岗位工种
                .addField("J.FixsalaryStandard AS fixsalaryStandard")//定薪标准/月
                .addField("J.SalaryStandard AS salaryStandard")//发薪标准/月
                .addField("J.FixedSalaryRatio AS fixedSalaryRatio")//固定薪资比例
                .addField("J.PerformanceRatio AS performanceRatio")//绩效薪资比例
                .addField("J.BasicSalary AS basicSalary")//基本底薪/月
                .addField("J.PositionSalary AS positionSalary")//岗位薪资/月
                .addField("J.PerbasedSalary AS perbasedSalary")//绩效薪资/月
                .addField("J.TransSubsidy AS transSubsidy")//交通补贴/月
                .addField("J.CateringSubsidy AS cateringSubsidy")//餐饮补贴/月
                .addField("J.JobPromotion AS jobPromotion")//岗位提奖/月
                .addField("J.QuarterlyBonus AS quarterlyBonus")//季度提奖/月
                .addField("J.AnnualBonus AS annualBonus")//年终奖标准（月）
                //岗位类别(0管理 1服务 2技术)
                .addField("CASE " +
                        "WHEN J.Category = 0 THEN '管理' " +
                        "WHEN J.Category = 1 THEN '服务' " +
                        "WHEN J.Category = 2 THEN '技术' " +
                        " ELSE '' END categoryTxt")
                //职级大类(0A 1B 2C 3D 4P)
                .addField("CASE " +
                        "WHEN J.Categories = 1 THEN 'A' " +
                        "WHEN J.Categories = 2 THEN 'B' " +
                        "WHEN J.Categories = 3 THEN 'C' " +
                        "WHEN J.Categories = 4 THEN 'D' " +
                        "WHEN J.Categories = 5 THEN 'P' " +
                        " ELSE '' END categoriesTxt")
                //岗位工种(0总经理 1副总经理 2责任月薪型员工 3绩效提奖型员工 4研发人员)
                .addField("CASE " +
                        "WHEN J.Type = 1 THEN '总经理' " +
                        "WHEN J.Type = 2 THEN '副总经理' " +
                        "WHEN J.Type = 3 THEN '责任月薪型员工' " +
                        "WHEN J.Type = 4 THEN '绩效提奖型员工' " +
                        "WHEN J.Type = 5 THEN '研发人员' " +
                        " ELSE '' END roleLevelTypeTxt")

            .addLeftJoin("TB_SocialSecurity S ON S.Id = A.SocialSecurityId")//社保管理表
                .addField("S.SoseBase AS soseBase")//社保基数
                //.addField("SUM(S.PiUnitMonth + S.UiUnitMonth + S.WiiUnitMonth) AS socialSecurityByCompany")//社保（单位）/月
                //.addField("SUM(S.PiRatioIndividual + S.UiIndividualMonth ) AS socialSecurityByPersonal")//社保（个人）/月
                .addField("S.PiUnitMonth AS piUnitMonth")
                .addField("S.UiUnitMonth AS uiUnitMonth")
                .addField("S.WiiUnitMonth AS wiiUnitMonth")
                .addField("S.PiRatioIndividual AS piRatioIndividual")
                .addField("S.UiIndividualMonth AS uiIndividualMonth")
                .addField("S.PiIndividualMonth AS piIndividualMonth")

            .addLeftJoin("TB_MedicalInsurance M ON M.Id = A.MedicalInsuranceId")//医保管理表
                .addField("M.MiBase AS miBase")//医保基数
                //.addField("SUM(M.MiUnitMoonth + M.MiUnitMonth) AS medicalInsuranceByCompany")//医保（单位）/月
                .addField("M.MiUnitMoonth AS miUnitMoonth")
                .addField("M.MiUnitMonth AS miUnitMonth")
                .addField("M.MiIndividualMonth AS medicalInsuranceByPersonal")//医保（个人）/月

            .addLeftJoin("TB_ProvidentFund P ON P.Id = A.AccumulationFundId")//公积金管理表
                .addField("P.HousingPfBase AS housingPfBase")//公积金基数
                .addField("P.PfUnitMonth AS providentFundByCompany")//公积金（单位）/月
                .addField("P.PfIndividualMonth AS providentFundByPersonal")//公积金（个人）/月

            .addLeftJoin("TB_Attendance AD ON AD.Id = A.AttendanceId")//考勤管理表
                .addField("AD.Type AS type")//考勤类型

                .setId(id)
                .queryFirstMap();
        return entity;
    }


    public Map<String, Object> setExtraParam(Map<String,Object> entity){
        Map<String, Object> extraParam = new HashMap<String, Object>();
        //关联数据
        if(entity.get("_ys_nameLinked")!=null)extraParam.put("_ys_nameLinked", entity.get("_ys_nameLinked"));
        if(entity.get("deptName")!=null)extraParam.put("deptName", entity.get("deptName"));
        if(entity.get("userState")!=null)extraParam.put("userState", entity.get("userState"));
        if(entity.get("orgName")!=null)extraParam.put("orgName", entity.get("orgName"));
        if(entity.get("rank")!=null)extraParam.put("rank", entity.get("rank"));
        if(entity.get("category")!=null)extraParam.put("category", entity.get("category"));
        if(entity.get("categories")!=null)extraParam.put("categories", entity.get("categories"));
        if(entity.get("roleLevelType")!=null)extraParam.put("roleLevelType", entity.get("roleLevelType"));
        if(entity.get("fixsalaryStandard")!=null)extraParam.put("fixsalaryStandard", entity.get("fixsalaryStandard"));
        if(entity.get("salaryStandard")!=null)extraParam.put("salaryStandard", entity.get("salaryStandard"));
        if(entity.get("fixedSalaryRatio")!=null)extraParam.put("fixedSalaryRatio", entity.get("fixedSalaryRatio"));
        if(entity.get("performanceRatio")!=null)extraParam.put("performanceRatio", entity.get("performanceRatio"));
        if(entity.get("basicSalary")!=null)extraParam.put("basicSalary", entity.get("basicSalary"));
        if(entity.get("positionSalary")!=null)extraParam.put("positionSalary", entity.get("positionSalary"));
        if(entity.get("perbasedSalary")!=null)extraParam.put("perbasedSalary", entity.get("perbasedSalary"));
        if(entity.get("transSubsidy")!=null)extraParam.put("transSubsidy", entity.get("transSubsidy"));
        if(entity.get("cateringSubsidy")!=null)extraParam.put("cateringSubsidy", entity.get("cateringSubsidy"));
        if(entity.get("jobPromotion")!=null)extraParam.put("jobPromotion", entity.get("jobPromotion"));
        if(entity.get("quarterlyBonus")!=null)extraParam.put("quarterlyBonus", entity.get("quarterlyBonus"));
        if(entity.get("annualBonus")!=null)extraParam.put("annualBonus", entity.get("annualBonus"));
        if(entity.get("soseBase")!=null)extraParam.put("soseBase", entity.get("soseBase"));
        //if(entity.get("socialSecurityByCompany")!=null)extraParam.put("socialSecurityByCompany", entity.get("socialSecurityByCompany"));
        //if(entity.get("socialSecurityByPersonal")!=null)extraParam.put("socialSecurityByPersonal", entity.get("socialSecurityByPersonal"));
        if(entity.get("miBase")!=null)extraParam.put("miBase", entity.get("miBase"));
        //if(entity.get("medicalInsuranceByCompany")!=null)extraParam.put("medicalInsuranceByCompany", entity.get("medicalInsuranceByCompany"));
        if(entity.get("medicalInsuranceByPersonal")!=null)extraParam.put("medicalInsuranceByPersonal", entity.get("medicalInsuranceByPersonal"));
        if(entity.get("housingPfBase")!=null)extraParam.put("housingPfBase", entity.get("housingPfBase"));
        if(entity.get("providentFundByCompany")!=null)extraParam.put("providentFundByCompany", entity.get("providentFundByCompany"));
        if(entity.get("providentFundByPersonal")!=null)extraParam.put("providentFundByPersonal", entity.get("providentFundByPersonal"));
        if(entity.get("type")!=null)extraParam.put("type", entity.get("type"));
        if(entity.get("categoryTxt")!=null)extraParam.put("categoryTxt", entity.get("categoryTxt"));
        if(entity.get("categoriesTxt")!=null)extraParam.put("categoriesTxt", entity.get("categoriesTxt"));
        if(entity.get("roleLevelTypeTxt")!=null)extraParam.put("roleLevelTypeTxt", entity.get("roleLevelTypeTxt"));
        if(entity.get("dingDingId")!=null)extraParam.put("dingDingId", entity.get("dingDingId"));
        if(entity.get("telephone")!=null)extraParam.put("telephone", entity.get("telephone"));
        if(entity.get("userStateTxt")!=null)extraParam.put("userStateTxt", entity.get("userStateTxt"));

        BigDecimal socialSecurityByCompany = BigDecimal.ZERO;//社保（单位）/月
        BigDecimal socialSecurityByPersonal = BigDecimal.ZERO;//社保（个人）/月
        BigDecimal medicalInsuranceByCompany = BigDecimal.ZERO;//医保（单位）/月

        if(entity.get("piUnitMonth")!=null){
            socialSecurityByCompany = socialSecurityByCompany.add(new BigDecimal(entity.get("piUnitMonth").toString()));
        }
        if(entity.get("uiUnitMonth")!=null){
            socialSecurityByCompany = socialSecurityByCompany.add(new BigDecimal(entity.get("uiUnitMonth").toString()));
        }
        if(entity.get("wiiUnitMonth")!=null){
            socialSecurityByCompany = socialSecurityByCompany.add(new BigDecimal(entity.get("wiiUnitMonth").toString()));
        }
        extraParam.put("socialSecurityByCompany",socialSecurityByCompany);
        if(entity.get("piIndividualMonth")!=null){
            socialSecurityByPersonal = socialSecurityByPersonal.add(new BigDecimal(entity.get("piIndividualMonth").toString()));
        }
        if(entity.get("uiIndividualMonth")!=null){
            socialSecurityByPersonal = socialSecurityByPersonal.add(new BigDecimal(entity.get("uiIndividualMonth").toString()));
        }
        extraParam.put("socialSecurityByPersonal",socialSecurityByPersonal);
        if(entity.get("miUnitMoonth")!=null){
            medicalInsuranceByCompany = medicalInsuranceByCompany.add(new BigDecimal(entity.get("miUnitMoonth").toString()));
        }
        if(entity.get("miUnitMonth")!=null){
            medicalInsuranceByCompany = medicalInsuranceByCompany.add(new BigDecimal(entity.get("miUnitMonth").toString()));
        }
        extraParam.put("medicalInsuranceByCompany",medicalInsuranceByCompany);


        return extraParam;
    }

    /*
     * 新增
     */
    @GetMapping("/toAdd")
    public String toAdd(Model model, HttpServletRequest request, HttpServletResponse response) {
        try {

            Map<String, Object> extraParam = new HashMap<String, Object>();
            //关联数据
            extraParam.put("status", 1);
            model.addAttribute("onProcess", 0);
            commonApiService.toAdd(model, new TbUserJobLevelManage(), MenuId.TB_UserJobLevelManage, extraParam, null);

            return "base/tbUserJobLevelManage/toAdd";
        }catch (Exception e) {
            logger.error("新增页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }

    /*
     * 编辑
     */
    @GetMapping("/toEdit")
    public String toEdit(Model model, HttpServletRequest request, HttpServletResponse response, Long id) {
        try {
            Map<String,Object> entity = getEntity(id);
            Map<String, Object> extraParam = setExtraParam(entity);
            model.addAttribute("onProcess", 0);
            String aa = commonApiService.toEdit(model,id, new TbUserJobLevelManage(), MenuId.TB_UserJobLevelManage, extraParam, null);
            
            if ("test".equals(MyConfig.getActive()) || "pro".equals(MyConfig.getActive())) {
                return "base/tbUserJobLevelManage/toEdit";
			} else {
				return aa;
			}

        }catch (Exception e) {
            logger.error("编辑页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }


    /*
     * 详情
     */
    @GetMapping("/toDetail")
    public String toDetail(Model model, HttpServletRequest request, HttpServletResponse response, Long id) {
        try {
            Map<String,Object> entity = getEntity(id);
            Map<String, Object> extraParam = setExtraParam(entity);
            model.addAttribute("onProcess", 1);
            return commonApiService.toDetail(model,id, new TbUserJobLevelManage(), MenuId.TB_UserJobLevelManage, extraParam, null);
        }catch (Exception e) {
            logger.error("详情页面出错：",e.getMessage(),e);
            return W.error(model, e.getMessage());
        }
    }




}






